/**
 * 
 */
package edu.bbk.muc.lifetracker.logging;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

/**
 * This class is reponsible for writing and storing files in format from a given
 * {@link Logger} using Android Exteranal storage.
 * 
 * @author irenatyler and romankirillov
 * 
 */
public class FileStorer {
  private String filename; // file name
  // Specific logger which provides text for file, format and other particulars
  // specific to that logger.
  private Logger logger;
  private File file;

  /**
   * Initialises this {@link FileStorer}'s fields, including creation of new
   * file and directory to write to.
   * 
   * @param logger
   *          Specific {@link Logger} which provides text for file, format and
   *          other particulars specific to that {@link Logger}.
   */
  public FileStorer(Logger logger) {
    this.logger = logger;
    filename = String.format("%1$s_log_%2$s%3$s", this.logger.getType(), 
        logger.getFromToDateTimeStamp(),
        this.logger.getFileExtension());
    Log.d("FileStorer, constructor","filename: " + filename);
    file = new File(getDirectory(), filename);
    Log.d("FileStorer, constructor","file full path: " + file.getAbsolutePath());
  }

  /**
   * Stores file in this {@link FileStorer} directory.
   * 
   * @return true if file was successfully stored and false otherwise.
   */
  public boolean storeFile() {
    // write file in the directory
    return writeFile(logger.getFileContent());
  }

  /**
   * Gets directory to store the file in.
   * 
   * @return directory to store the file in.
   */
  private File getDirectory() {
    File dir = Environment.getExternalStoragePublicDirectory(Context.DOWNLOAD_SERVICE);
    // make directory if doesn't exist already
    dir.mkdirs();
    return dir;
  }

  /**
   * Creates file in given directory and writes to created file.
   * 
   * @param text
   *          Text to write to the file.
   * @return true if file was successfully written and false otherwise.
   */
  private boolean writeFile(String text) {

    boolean success = false;

    BufferedWriter bw;
    try {
      bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
      bw.write(text);
      bw.close();
      success = true;
    } catch (Exception e) {
      Log.e("FileStorer", "Failed writing file: " + e.getMessage());
    }
    return success;
  }

  /**
   * Gets file name.
   * 
   * @return file name.
   */
  public String getFilename() {
    return filename;
  }

  /**
   * Gets this {@link FileStorer}'s file.
   * 
   * @return this {@link FileStorer}'s file.
   */
  public File getFile() {
    return file;
  }

}
